package com.boss.sever;

import java.io.BufferedWriter;
import java.io.FileWriter;

/**
 * 发送文件消息处理器，处理服务器发送文件的请求
 * @author 郑炆杰
 */
public class SendFileHandler extends com.boss.sever.AbstractMessageHandler {
    public SendFileHandler(Server server, String clientId, String message) {
        super(server, clientId, message);
    }

    @Override
    public void handle() {
        try {
            String encryptedContent = server.getClientHandler(clientId).readMessage();
            String content = server.decrypt(encryptedContent);
            String[] parts = message.split(" ");
            String target = parts[1];
            String filePath = parts[2];

            if ("@all".equals(target)) {
                server.sendMessageToAll("开始接收文件: " + filePath);
                server.sendMessageToAll(content);
                server.sendMessageToAll("文件接收完成: " + filePath);
            } else {
                server.sendMessageToClient(target, "开始接收文件: " + filePath);
                server.sendMessageToClient(target, content);
                server.sendMessageToClient(target, "文件接收完成: " + filePath);
            }

            try (BufferedWriter writer = new BufferedWriter(new FileWriter(filePath + "ddd"))) {
                writer.write(content);
            }
            System.out.println("文件 " + filePath + " 接收并解密完成");
        } catch (Exception e) {
            System.out.println("文件接收失败");
        }
    }
}
